<?php
class Core_Common_Views_Helpers_Acl extends Zend_View_Helper_Abstract {
	
	/***
	 * @var Zend_Acl
	 */
	protected $_acl;
	/***
	 * @var Zend_Auth
	 */
	protected $_auth;
	/***
	 * @var string
	 */
	protected $_controllername;
	/***
	 * @var Zend_Controller_Action
	 */
	protected $_action;
	
	public function __construct(Zend_View_Interface $view=null,array $options = array()) {
		$auth = Zend_Auth::getInstance();
		$this->_auth = $auth;
		if(isset($options['acl']))
			$this->_acl = $options['acl'];
		else {
			$cache = Core_Common_Cache::getInstance();
			$acl = $cache->acl;
			if(isset($acl)) {
				$this->_acl = $acl;
			}
		}
		
	}
	public $view;
	
	public function setView(Zend_View_Interface $view) {
		$this->view = $view;
	}
	/***
	 * Hook into Action Controller init workflow
	 */
	public function init() {
		$this->_action = $this->getActionController();
		$this->_controllername = $this->_action->getRequest()->getControllerName();
		if(!$this->_acl->has($this->_controllername)) {
			$this->_acl->addResource(new Zend_Acl_Resource($this->_controllername));
		}
	}
	/***
	 * Hook into Action Controller preDispatch workflow 
	 */
	public function preDispatch() {
		$role = 'guest';
		if($this->_auth->hasIdentity()) {
			$user = $this->_auth->getIdentity();
			if (isset($user) && is_object($user))
				$role = $this->_auth->getIdentity()->role;
		}
		else {
			$request->setControllerName('auth');
			$request->setModuleName('default');
			$request->setActionName('login');
			$request->setDispatched(false);
		}
		
		$request = $this->_action->getRequest();
		$controller = $request->getControllerName();
		$action = $request->getActionName();
		$module = $request->getModuleName();
		$this->_controllername = $controller;
		
		$resource = $controller;
		$privilege = $action;
		if(!$this->_acl->has($resource))
			$resource=null;
		
		if(!$this->_acl->isAllowed($role,$resource,$privilege)) {
			$request->setControllerName('auth');
			$request->setModuleName('default');
			$request->setActionName('login');
			$request->setDispatched(false);
		}
	}
	
	public function allow ($role,$privilege) {
		$resource = $this->_controllername;
		$this->_acl->allow($role,$resource,$privilege);
		return $this;
	}
	
	public function deny($role,$privilege) {
		$resource = $this->_controllername;
		$this->_acl->deny($role,$resource,$privilege);
		return $this;
	}
	
	public function getUserId() {
		$auth = Zend_Auth::getInstance();
		if($auth->hasIdentity()) {
			$identity = $auth->getIdentity();
			return $identity->id;
		}
		else 
			return null;	
	}
	public function getUser() {
		$auth = Zend_Auth::getInstance();
		if($auth->hasIdentity()) {
			$identity = $auth->getIdentity();
			return $identity;
		}
		else 
			return null;	
	}
}
?>